import request from '@/utils/request'
import store from '@/store/index.js'
import { Notification } from 'element-ui'
import enc from '@/utils/encrypt'

const tokenKey = 'Authorization'

/**
 * 用户登录
 */
export function login (username, password, code, uuid) {
  let param = new URLSearchParams()
  param.append('username', username)
  param.append('password', encryptPwd(password))
  return request({
    url: '/login',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Identify-Code': encryptPwd(uuid + '_' + code)
    },
    data: param
  })
}

export function register (email, pwd, repwd, code, uuid) {
  let registerData = {
    account: email,
    password: encryptPwd(pwd),
    rePassword: encryptPwd(repwd),
    userName: email,
    email: email
  }
  return request({
    url: '/user',
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      'Identify-Code': encryptPwd(uuid + '_' + code)
    },
    data: registerData
  })
}

export function resetPassword (pwd, repwd) {
  return request({
    url: '/user/password',
    method: 'post',
    data: {
      password: encryptPwd(pwd),
      rePassword: encryptPwd(repwd)
    }
  })
}

function encryptPwd (password) {
  return enc.encrypt(password)
}

export function getInfo (id) {
  return request({
    url: '/user/' + id,
    method: 'get',
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

export function getUserInfoByToken () {
  return request({
    url: '/user',
    method: 'get',
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

export function logout (token, refreshToken) {
  return request({
    url: '/logout',
    method: 'get',
    headers: {
      'Authorization': token,
      'RefreshAuthorization': refreshToken
    }
  })
}

/**
 * 是否已登录
 * @returns {boolean}
 */
export function isLogged () {
  return store.getters.token !== ''
}

/**
 * 检查登录状态
 */
export function checkLogin () {
  console.log('进入登录检查')
  if (!store.getters.token) {
    console.log('- Token不存在，检验未通过')
    return false
  }
  if (!store.getters.refreshToken) {
    console.log('- refreshToken不存在，检验未通过')
    return false
  }
  if (store.getters.logged) {
    console.log('- 已登录，检验通过')
    return true
  }
  if (!store.getters.currentUserId) {
    console.log('- 未登录，且当前用户ID不存在，检验未通过')
    return false
  }
  return false
}

export function getCode (len = 4) {
  return request({
    url: '/common/identify/' + len,
    method: 'get'
  })
}

export function updateUserInfo (formData) {
  let param = {}
  if (formData.email) {
    param['email'] = formData.email
  }
  if (formData.userName) {
    param['username'] = formData.userName
  }
  return request({
    url: '/user/' + store.getters.currentUserId,
    method: 'put',
    params: param
  })
}

/**
 * 用户鉴权
 */
export function auth (token = localStorage.getItem(tokenKey)) {
  if (!token) {
    return null
  }
  let authResult = null
  request({
    method: 'get',
    url: '/common/token',
    headers: {
      tokenKey: token
    }
  }).then(res => {
    let result = res.data
    console.log(result)
    // 授权成功
    if (result.code === '00000') {
      authResult = res.data
      store.commit('updateRole', result.data.roles)
      store.commit('updatePermission', result.data.permissions)
      store.commit('updateUser', result.data)
    } else {
      Notification.error({
        title: result.msg,
        message: '错误码：' + result.code
      })
    }
  }).catch(err => {
    console.log(err)
    Notification.error({
      title: '访问失败',
      message: err.message
    })
    authResult = null
  })

  return authResult
}
